import { ccs } from "./services";

 export class GlobalFunc {

    //生成性别
    getSexStr(sex: "b" | "g") {
        return sex + Math.floor(Math.random() * 10 + 1);
    }
    getLocalData(key: string) {
        if(key) {
            return JSON.parse(cc.sys.localStorage.getItem(key));
        }
    }
    clearData(key?: string) {
        if(key) {
            return JSON.parse(cc.sys.localStorage.setItem(key, ""));
        }else {
            cc.sys.localStorage.clear();
        }
    }
    saveData(key: string, data: any) {
        if(!key || !data) {
            return false;
        }
        cc.sys.localStorage.setItem(key, JSON.stringify(data));
        return true;
    }
    getItemKey(item:any) {
        return item.id;
    }
    
     doCallback (func?:Function, target?:object, t1?:any, t2?:any, t3?:any, t4?:any, t5?:any, t6?:any) {
         if(func) {
             return func.call(target, t1, t2, t3, t4, t5, t6);
         }
         return null;
     }
 
     doEventCallback(event?:cc.Component.EventHandler, t1?:any, t2?:any, t3?:any, t4?:any, t5?:any, t6?:any) {
         if(!event) {
             return null;
         }
 
         if(event.target && event.handler) {
             let component = event.target.getComponent(event.component || (event as any)._componentName);
             if(component) {
                 if(event.customEventData) {
                     return this.doCallback(component[event.handler], component, event.customEventData, t1, t2, t3, t4, t5);
                 } else {
                     return this.doCallback(component[event.handler], component, t1, t2, t3, t4, t5, t6);
                 }
             }
         }
         return null;
     }
 
     newEventHandler(node: cc.Node, component:string, handler:string, event?:cc.Component.EventHandler) {
         if(!event) {
             event = new cc.Component.EventHandler();
         }
         event.target = node;
         event.component = component;
         event.handler = handler;
         return event;
     }
 
     // 将一个节点下面的子节点保存在根目录上方便调用(注意：根节点只遍历一次)
     extendNodeName (root:any, node?:cc.Node, isChild?:boolean | undefined) {
         if(!node) {
             node = root;
         }
         if(root.__isExtendNodeName) {
             return ;
         }
         let children = node.children;
         for(let i = 0, len = children.length; i < len; i++) {
             let nodeName = children[i].name;
             if(nodeName) {
             root[nodeName] = children[i];
             }
             this.extendNodeName(root, children[i], true);
         }
         if(!isChild) {
             root.__isExtendNodeName = true;
         }
     }
 
     //////////////////////// 类型判断
     isFunction(obj:any) {
         return typeof obj == 'function';
     }
 
     isArray(obj:any) {
         return Array.isArray(obj) ||
         (typeof obj === 'object' && Object.prototype.toString.call(obj) === '[object Array]');
     }
     handlerCount(value, count, maxCount: number = 100) {
        if(isNaN(value) || isNaN(count)) {
            return ;
        }
        let tmp = value + count;
        if(tmp < 0) {
            tmp = 0;
        } else if(tmp > maxCount) {
            tmp = maxCount;
        }
        return tmp;
    }
     isObject(obj:any) {
         return obj.__nativeObj !== undefined ||
             ( typeof obj === "object" && Object.prototype.toString.call(obj) === '[object Object]' );
     }
 
     //////////////////////////////////////////// 数组相关
     //不需要区分内容的类型
     findListIdx(list: any[], object: any):number {
         for(let i = 0, len = list.length; i < len; i++) {
             if(list[i] == object) {
                 return i;
             }
         }
         return -1;
     }
     randomColor() {
        return new cc.Color(this.randomInt(0, 255), this.randomInt(0, 255), this.randomInt(0, 255));
    };

     findListIdxById(list: any[], id: any): number {
         return list.findIndex(val => val.id == id);
     }
     // 判断对象是否为空
     isEmptyObject (obj?:object) {
         if(!obj) {
             return true;
         }
         for (let key in obj) {
             if(obj[key] != null) {
                 return false;
             }
         }
         return true;
     }
 
     toValuesArray(object:any) {
         if(this.isArray(object)) {
             return object;
         }
         let array = [];
         for(let k in object) {
             (object[k] !== undefined && object[k] !== null) && array.push(object[k]);
         }
         return array;
     }
 
     toKeyArray(object:any) {
         if(this.isArray(object)) {
             return object;
         }
 
         let array = [];
         for(let k in object) {
             (object[k] !== undefined && object[k] !== null) && array.push(k);
         }
         return array;
     }
 
     isValueNull(value:any) {
         return value == undefined || value == null;
     }
 
     //////////////////////////////////////////// 定时器相关
     performWithDelay(node:cc.Node, callback:Function, delay:number = 0, target?:object) {
         return cc.tween(node).delay(delay).call(()=>{
             this.doCallback(callback, target, node);
         }).start();
     }
 
     schedule (node:cc.Node, callback:Function, delay:number = 0, target?:object) {
         return cc.tween(node).repeatForever(
             cc.tween().delay(delay).call(()=>{
                 this.doCallback(callback, target, node);
             })).start();
     }
 
     _recordTimeoutId = {};             // 记录系统的定时器
     performWithDelayEx(key:string, callback:Function, delay:number = 0, target?:object) {
         this.clearDelayEx(key);
         let id = setTimeout(()=>{
             delete this._recordTimeoutId[key];
             this.doCallback(callback, target);
         }, delay * 1000);
         this._recordTimeoutId[key] = id;
     }
 
     clearDelayEx(key:string) {
         let id = this._recordTimeoutId[key];
         if(id) {
             clearTimeout(id);
             delete this._recordTimeoutId[key];
         }
     }
 
     // 清理所有的系统定时器
     clearAllDelayEx() {
         for(let key in this._recordTimeoutId) {
             clearTimeout(this._recordTimeoutId[key]);
         }
         this._recordTimeoutId = {};
     }
 
     _recordIntervalId = {};
     clearScheduleEx(key:string) {
         let id = this._recordIntervalId[key];
         if(id) {
             clearInterval(id);
             delete this._recordIntervalId[key];
         }
     }
 
     scheduleEx(key:string, callback:Function, delay:number = 0, target?:object) {
         this.clearScheduleEx(key);
         let id = setInterval(()=>{
             this.doCallback(callback, target);
         }, delay * 1000);
         this._recordIntervalId[key] = id;
     }
 
     clearAllScheduleEx() {
         for(let key in this._recordIntervalId) {
             clearInterval(this._recordIntervalId[key]);
         }
         this._recordIntervalId = {};
     }
 
     //////////////////////////////////////////// 数值相关
     // 判断是否是整数
     // 超过32位的数值无能为力
     isInteger32(val:number) {
         return (val | 0) === val;
     }
 
     // 整数不添加0  val number  取几位小数
     toFixed(val:number, num:number = 0):string {
         if(this.isInteger32(val)) {
             return val + '';
         }
         let numStr = val.toFixed(num);
         // 去掉小数点末尾的0
         let idx = numStr.indexOf('.');
         if(idx > 0) {
             for(let i = idx + 1, len = numStr.length; i < len; i++) {
                 if(numStr[i] != '0') {
                     return numStr;
                 }
             }
 
             return numStr.substr(0, idx);
         }
         return numStr;
     }
 
     //数字转中文
     chnNumChar = ['零','一', '二', '三', '四', '五', '六', '七', '八', '九'];
     chnUnitSection = ["","万","亿","万亿","亿亿"];
     chnUnitChar = ["","十","百","千"];
     sectionToChinese(section:number) {
         let strIns = '', chnStr = '';
         let unitPos = 0;
         let zero = true;
         while(section > 0){
             var v = section % 10;
             if(v === 0){
                 if(!zero){
                     zero = true;
                     chnStr = this.chnNumChar[v] + chnStr;
                 }
             }else{
                 zero = false;
                 strIns = this.chnNumChar[v];
                 strIns += this.chnUnitChar[unitPos];
                 chnStr = strIns + chnStr;
             }
             unitPos++;
             section = Math.floor(section / 10);
         }
         return chnStr;
     }
 
     numberToChinese(num:number) {
         let unitPos = 0;
         let strIns = '', chnStr = '';
         let needZero = false;
         if(num === 0){
             return this.chnNumChar[0];
         }
 
         while(num > 0){
             var section = num % 10000;
             if(needZero){
                 chnStr = this.chnNumChar[0] + chnStr;
             }
             strIns = this.sectionToChinese(section);
             strIns += (section !== 0) ? this.chnUnitSection[unitPos] : this.chnUnitSection[0];
             chnStr = strIns + chnStr;
             needZero = (section < 1000) && (section > 0);
             num = Math.floor(num / 10000);
             unitPos++;
         }
         return chnStr;
     }
 
     __getNumPart(num:number|string, max:number = 1) {
         num = Number(num);
         if(num < 10){
             max = Math.min(max, 3);
             num = (num *Math.pow(10,max))/Math.pow(10,max);
         }else if(num < 100){
             max = Math.min(max, 2);
             num = (num *Math.pow(10,max))/Math.pow(10,max);
         }else if(num < 1000){
             max = Math.min(max, 1);
             num = (num *Math.pow(10,max))/Math.pow(10,max);
         }
         return num;
     }
 
     getOmitNum(num:number|string, max?:number) {
         num = Number(num);
         let sort = 1;
         if(num < 0 ) {
            sort = -1;
            num = Math.abs(num);
         }
        if(num > 1000000000000){
            num = this.__getNumPart(num/1000000000000, max);
            return (sort * num).toFixed(2) + "万亿";
        }else if(num > 100000000){
             num = this.__getNumPart(num/100000000, max);
             return (sort * num).toFixed(2) + "亿";
         }else if(num > 10000){
             num = this.__getNumPart(num/10000, max);
             return (sort * num).toFixed(2) + "万";
         }
         return (num * sort).toFixed(1);
     }
     randomInt(min: number = 0, max: number) {
        return Math.round(Math.random()*(max-min)+min);
    }
     //生成随机数
     zero(time){
        if (time<10) {
             return time="0"+time;
         }else{
             return time;
         }
    }
    randomId(){
    var five="";
     var now = new Date();
     var y=now.getFullYear().toString();
     var M=this.zero(now.getMonth()+1);
     
     var d=this.zero(now.getDate())
     
     var hour=this.zero(now.getHours().toString());
     var m=this.zero(now.getMinutes().toString());

     var s=this.zero(now.getSeconds().toString());
     
     for (var i = 0; i < 5; i++) {
         five+=Math.round(Math.random()*9)
     }
    
     var str = y + M+d+hour+m+s+five;
        return str;
    
    }
     getCountStr(count:number|string) {
         count = Number(count);
         let coutStr = "";
         if(count > 100000000){
             coutStr += (parseInt(count/10000000 + '')/10).toFixed(1)+"亿";
         }else if(count > 10000000){
             coutStr += parseInt(count/10000 + '')+"万";
         }else if(count > 10000){
             coutStr += (parseInt(count/1000 + '')/10).toFixed(1)+"万";
         }else{
             coutStr += count;
         }
         return coutStr;
     }
     getDistanceTime (dateTime:number, lastTime:number = 0) {
        return (dateTime - lastTime) * 0.001;
    }
    // 获取距离某个时间点的剩余时间 单位秒
    getRemainingTime(hour:number, nowTime?: Date) {
        if(!nowTime) {
            nowTime = new Date();
        } 
        let endTime:Date = null;
        if(nowTime.getHours() < hour) {
            endTime = new Date(nowTime.getFullYear(), nowTime.getMonth(), nowTime.getDate(), hour, 0, 0, 0);
        } else {
            endTime = new Date(nowTime.getFullYear(), nowTime.getMonth(), nowTime.getDate() + 1, hour, 0, 0, 0);
        }
        return (endTime.getTime() - nowTime.getTime()) * 0.001;
    }
     // 计算区间的百分比
     calcRangeRate(value:number, min:number, max:number) {
         if(min > max) {
             let temp = min;
             min = max;
             max = temp;
         }
         return (value - min) / (max - min);
     }
 
     checkFish(func, target?:object) {
         this.doCallback(func, target);
     }
     getEffectString(obj: Object): string {

        let effect = "", str = ""
        for(let key in obj) {
            str = obj[key];
            if(key == "lifeTime") {
                str = (obj[key] * 31).toFixed(2) + "天";
            }
            effect += `${ccs.dataMgr.getAttributeNameById(key).name}:${str}，`;
        }
        return effect || "神仙效果，试试";
     }
 }